<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/7/10
 * Time: 14:56
 */
namespace backend\controllers;

use backend\models\LogBackend;
use backend\models\LogCategory;
use backend\models\LogSms;
use Yii;
use yii\web\AdminController;
use common\helps;
use common\helps\tools;
use backend\models\LogWeb;

class SysLogController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'SysLog';
    //短信日志
    public $service_sms = 'SysSmsLog';
    /**************************************后台操作日志查询***********************************************************/
    /**
     *后台操作日志查询
     */
    public function actionBackend(){
        //读到业务数据
        $query = LogCategory::find()->where("log_type = 'backend'")->all();
        $this->saveLog($this->service,'日志查询页','VIEW','');                     //日志
        return $this->render('backend',['serviceList'=> $query]);
    }

    /**
     * 查询操作日志数据
     */
    public function actionBackendLoadList(){

        try{

            $data = Yii::$app->request->post();
            $condition = array();
            $condition[] = 'and';
            //业务条件
            if(!empty($data['service'] || $data['service'] !='')){
                $condition[] = ['log.log_category_key' => $data['service']];
            }
            //add by allen.qiang 20171228 标题条件 start
            if(!empty($data['log_title'])){
                $condition[] = ['like', 'log.log_title', $data['log_title']];
            }

            //ip条件
            if(!empty($data['ip'] || $data['ip'] !='')){
                $condition[] = ['log.ip' => $data['ip']];
            }
            //add by allen.qiang 20171228 标题条件 end
            //日期条件
            if(!empty($data['dateval'] || $data['dateval'] !='')){
                $date_arr = explode (' - ',  $data['dateval']);
                $date_arr[0] = $date_arr[0] .= ' 00:00:00';
                $date_arr[1] = date('Y-m-d 00:00:00',strtotime($date_arr[1]. "+ 1 day"));
                $condition[] = ['between', 'log.create_time', $date_arr[0],$date_arr[1]];
            }
            //操作人条件
            if(!empty($data['creator'])){
                $condition[] = ['like', 'log.creator', $data['creator']];
            }

            $query = LogBackend::find()->where($condition)->alias('log');
            $count = $query->count();

            $list = $query->offset($data['start'])->limit($data['length'])
                ->leftJoin('j_log_category as cat',"log.log_category_key = cat.log_category_key and cat.log_type = 'backend' ")
                ->select('log.*,cat.log_category_name')
                ->orderBy(array('log.id'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();

            if(empty($list)){
                $list = array();
            }

            foreach ($list as &$value) {
                $value['content'] = mb_substr($value['content'] , 0 , 30,'utf-8');
            }
            //相关参数   http://datatables.club/manual/server-side.html
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $list;
            return \yii\helpers\Json::encode($result);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod allen.qiang 20180112 异常处理，日志优化 end
            throw new \Exception('操作失败');
            //$this->retJson('系统异常',9003);
        }
    }

    /**
     * 根据id获取后台操作日志详细内容
     */
    public function actionBackendLoadInfo(){

        try{
            $data = Yii::$app->request->post();

            if(empty($data['id'] || $data['id'] !='')){
                $this->retJson('参数错误！',9003);
            }

            $result = LogBackend::findOne(array('id'=>$data['id']));
            $this->retJson($result->content,200);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('系统异常',9003);
        }
    }


    /**************************************短信日志查询***********************************************************/
    /**
     *后台操作日志查询
     */
    public function actionSms(){
        $this->saveLog($this->service_sms,'短信日志查询页','VIEW','');                     //日志
        return $this->render('sms',['Balance'=> $this->getSmsBalance()]);
    }

    /**
     * 查询当前短信余额（剩余条数）
     * @return string
     */
    private function getSmsBalance(){

        $strUrl = 'http://175.102.15.131/msg/QueryBalance?account=yungui&pswd=TZV0rLL@';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $strUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);

        $result = explode("\n", $output) ;
        if(explode(",", $result[0])[1] == 0 ){
            $result_1 = explode(",", $result[1])[1];
            return '当前短信剩余：' . $result_1 . '条';
        }else{
            return '';
        }
    }

    /**
     * 查询短信日志数据
     */
    public function actionSmsLoadList(){

        try{
            $data = Yii::$app->request->post();
            $condition = array();
            $condition[] = 'and';
            //手机条件
            if(!empty($data['mobile'] || $data['mobile'] !='')){
                $condition[] = ['mobile' => $data['mobile']];
            }
            //状态条件
            if(!empty($data['sms_status'] || $data['sms_status'] !='')){
                $condition[] = ['sms_status' => $data['sms_status']];
            }
            //日期条件
            if(!empty($data['dateval'] || $data['dateval'] !='')){
                $dateval = explode (' - ',  $data['dateval']);
                $condition[] = ['between', 'create_time', $dateval[0],$dateval[1]];
            }

            $query = LogSms::find()->where($condition);
            $count = $query->count();

            $list = $query->offset($data['start'])->limit($data['length'])
                ->orderBy(array('id'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();

            if(empty($list)){
                $list = array();
            }

            //相关参数   http://datatables.club/manual/server-side.html
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $list;
            return \yii\helpers\Json::encode($result);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod allen.qiang 20180112 异常处理，日志优化 end
            throw new \Exception('操作失败');
        }
    }

    public function actionFrontend(){
        $this->saveLog($this->service,'前台访问日志查询页','VIEW','');
        return $this->render('frontend');
    }
    
    /**
     * 查询前台访问日志数据
     */
    public function actionFrontendLoadList(){
        try{
            
            $data = Yii::$app->request->post();
            $condition = array();
            $condition[] = 'and';
            //来源类型
            if(tools::arrayHasValue($data,'source_type') && $data['source_type'] != ''){
                $condition[] = ['source_type' => $data['source_type']];
            }
            //登录名
            if(tools::arrayHasValue($data,'user_name') && $data['user_name'] != ''){
                $condition[] = ['like', 'user_name', $data['user_name']];
            }

            //日期条件
            if(tools::arrayHasValue($data,'reservationtime') && $data['reservationtime'] != ''){
                $date_arr = explode (' - ',  $data['reservationtime']);
                $date_arr[0] = $date_arr[0] .= ' 00:00:00';
                $date_arr[1] = date('Y-m-d 00:00:00',strtotime($date_arr[1]. "+ 1 day"));
                $condition[] = ['between', 'create_time', $date_arr[0],$date_arr[1]];
            }
            //追踪代码
            if(tools::arrayHasValue($data,'tracker_code') && $data['tracker_code'] != ''){
                $condition[] = ['tracker_code'=>$data['tracker_code']];
            }
            //ip
            if(tools::arrayHasValue($data,'ip') && $data['ip'] != ''){
                $condition[] = ['ip'=>$data['ip']];
            }
            //key1
            if(tools::arrayHasValue($data,'key1') && $data['key1'] != ''){
                $condition[] = ['key1'=>$data['key1']];
            }
            //key2
            if(tools::arrayHasValue($data,'key2') && $data['key2'] != ''){
                $condition[] = ['key2'=>$data['key2']];
            }
            //key3
            if(tools::arrayHasValue($data,'key3') && $data['key3'] != ''){
                $condition[] = ['key3'=>$data['key3']];
            }
            $query = LogWeb::find()->where($condition)->alias('log');
            $count = $query->count();
            $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
            $list = $query->offset($data['start'])->limit($data['length'])->orderBy(
                [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $list;
            return \yii\helpers\Json::encode($result);
            
        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod allen.qiang 20180112 异常处理，日志优化 end
            throw new \Exception('操作失败');
        }
    }
}